#include "./bitmap.h"

using namespace MiniUI;
using namespace MiniUI::Type;

Bitmap::Bitmap()
: m_pBits(nullptr)
, m_bInnerBits(true)
{
}

Bitmap::~Bitmap()
{
	Destroy();
}

void Bitmap::Rebuild(const Type::MiniSize& size, lpvoid pBits)
{
    Destroy();
    m_pBits = pBits;
    m_bInnerBits = false;

    m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.cx, size.cy);
    m_bitmap.setPixels(m_pBits);
    m_bitmap.setIsOpaque(false);
}

void Bitmap::Rebuild(const MiniSize& size)
{
    Destroy();
    m_pBits = malloc(size.cx * size.cy * 4);
    m_bInnerBits = true;

    m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.cx, size.cy);
    m_bitmap.setPixels(m_pBits);
    m_bitmap.setIsOpaque(false);
}

lpvoid Bitmap::GetBytes() const
{
	return m_pBits;
}

uint Bitmap::GetWidthBytes() const
{
	return m_bitmap.rowBytes();
}

void Bitmap::GetBitmapSize(MiniSize& size) const
{
    size.cx = m_bitmap.width();
    size.cy = m_bitmap.height();
}

void* Bitmap::GetBitmapDevice() const
{
    return (void*)(&m_bitmap);
}

lpvoid Bitmap::LockBits(const MiniRect& rect)
{
    return (byte*)(m_pBits) + rect.left * sizeof(miniARGB) + rect.top * m_bitmap.rowBytes();
}

void Bitmap::UnlockBits()
{
}

void Bitmap::Destroy()
{
	if (m_bInnerBits && m_pBits)
	{
		free(m_pBits);
		m_pBits = nullptr;
	}
}